package playing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class showfrends extends JFrame {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/ZUT";
    private static final String USER = "root";
    private static final String PASS = "123456";

    private JPanel panel;

    public showfrends() {
        super("User Information");

        panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        // 添加关闭按钮
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
            }
        });

        panel.add(closeButton); // 将关闭按钮添加到面板

        getContentPane().add(panel);
        setSize(300, 250);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //setLocationRelativeTo(null); // 将窗口居中显示
        setVisible(true);
    }

    public void printAllUsersByIdList(List<Integer> userIdList) {
        for (int userId : userIdList) {
            printUserById(userId);
        }
        // 重新绘制窗口，以显示新添加的用户信息
        panel.revalidate();
        panel.repaint();
    }

    private void printUserById(int userId) {
        String sql = "SELECT username FROM users WHERE users_id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    String username = rs.getString("username");
                    JLabel userInfoLabel = new JLabel("用户ID: " + userId + ", 用户姓名: " + username);
                    panel.add(userInfoLabel); // 将Label添加到panel中显示
                } else {
                    JLabel notFoundLabel = new JLabel("用户ID " + userId + " 未找到对应的用户");
                    panel.add(notFoundLabel); // 用户未找到时的提示
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            showfrends frame = new showfrends();
            // 示例用法：假设你有一个用户ID列表
            List<Integer> userIds = List.of(1, 2, 3);
            frame.printAllUsersByIdList(userIds);
        });
    }
}
